from twisted.web import http

from urlparse import urlunparse
from datetime import datetime

def _parse(url, defaultPort=None):
    """
    Split the given URL into the scheme, host, port, and path.

    Stolen from Twisted.
    """
    url = url.strip()
    parsed = http.urlparse(url)
    scheme = parsed[0]
    path = urlunparse(('', '') + parsed[2:])

    if defaultPort is None:
        if scheme == 'https':
            defaultPort = 443
        else:
            defaultPort = 80

    host, port = parsed[1], defaultPort
    if ':' in host:
        host, port = host.split(':')
        try:
            port = int(port)
        except ValueError:
            port = defaultPort

    if path == '':
        path = '/'

    return scheme, host, port, path

class LockedError(Exception):
    def __init__(self, time):
        self.time = time
    def __str__(self):
        repr(self.time)

# XXX Add tracking switch for high priority targets
class TURP(object):
    """
    A TURP (Transitory Uniform Resource Profile) represents a web resource and
    the metadata associated with it as profiled over a well-defined period of
    time. Multiple TURPs may exist for the same resource.
    """
    
    def __init__(self, tracked=0):
        self.opened = datetime.now()
        self.directives = {}
        self.state = {}
        self.closed = None

    def setURL(self, url):
        self.url = url
        scheme, host, port, path = _parse(url)
        if scheme and host:
            self.scheme = scheme
            self.host = host
            self.port = port
        self.path = path

    def addDirective(self, directive):
        pass

    def lock(self):
        self.closed = datetime.now()

    def __setattr__(self, name, value):
        if hasattr(self, 'closed') and self.closed is not None:
            print "%s was locked at %s" % (repr(self), str(datetime.now().time()))
            raise LockedError(self.closed)
        else:
            object.__setattr__(self, name, value)
